package com.beiing.tianshuai.tianshuai.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Jinni on 2017/10/26 0026.
 */

public class HtmlUtils {
    /**
     * @param s html代码
     * @return 获得图片
     */
    private static List<String> getImg(String s) {
        String regex;
        List<String> list = new ArrayList<>();
        regex = "<img src=\"(.*?)\"";
        Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
        Matcher ma = pa.matcher(s);
        while (ma.find()) {
            list.add(ma.group());
        }
        return list;
    }

    /**
     * 返回存有图片地址的数组
     *
     * @param tar html代码
     * @return 结果
     */
    public static String[] getHtmlImageSrc(String tar) {
        List<String> imgList = getImg(tar);

        String res[] = new String[imgList.size()];

        if (imgList.size() > 0) {
            for (int i = 0; i < imgList.size(); i++) {
                int begin = imgList.get(i).indexOf("\"") + 1;
                int end = imgList.get(i).lastIndexOf("\"");
                String url[] = imgList.get(i).substring(begin, end).split("/");
                res[i] = url[url.length - 1];
            }
        }
        return res;
    }
}
